package com.ruiysoft.website.service;

import com.alibaba.fastjson.JSON;
import com.ruiysoft.website.entity.CmsLog;
import com.ruiysoft.website.mapper.CmsLogMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Logger;

/**
 * Created by liudh on 2018/11/16.
 */

// 优先级数字越小越高
@Order(1)
@Aspect
@Component
public class LogAspect {
    /*
    使用@Before在切入点开始处切入内容
    使用@After在切入点结尾处切入内容
    使用@AfterReturning在切入点return内容之后切入内容（可以用来对处理返回值做一些加工处理）
    使用@Around在切入点前后切入内容，并自己控制何时执行切入点自身的内容
    使用@AfterThrowing用来处理当切入内容部分抛出异常之后的处理逻辑
     */

    @Autowired
    CmsLogMapper cmsLogMapper;

    private Logger logger = Logger.getLogger(getClass().getName());
    ThreadLocal<Long> startTime = new ThreadLocal<>();


    @Pointcut("execution(public * com.ruiysoft.website.controller.*Controller.*(..))")
    public void logAspect(){}

    @Before("logAspect()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        logger.info("调用前:");
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

        CmsLog cmsLog = new CmsLog();
        cmsLog.setEnterpriseId(1);
        cmsLog.setType(request.getRequestURL().toString());
        cmsLog.setAction1(request.getRemoteAddr());
        cmsLog.setAction2(JSON.toJSONString(joinPoint.getArgs()));
        cmsLog.setCreateTime(new Date());
//        cmsLogMapper.insert(cmsLog);

    }

//    @Around("logAspect()")
//    public Object around(ProceedingJoinPoint point) throws Throwable {
//        return null;
//    }

    @AfterReturning(returning = "ret", pointcut = "logAspect()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("调用后:");
        if(ret != null)
            logger.info(ret.toString());
        logger.info("耗时: " + (System.currentTimeMillis() - startTime.get()) + " 毫秒");

        logger.info("");

    }
}
